//
//  QLRecordPlayer.m
//  WeiMiLan
//
//  Created by anan on 15/3/19.
//  Copyright (c) 2015年 Mac. All rights reserved.
//

#import "QLRecordPlayer.h"

@implementation QLRecordPlayer

static QLRecordPlayer* instance;

+ (QLRecordPlayer*)shareInstance
{
    if (instance==nil) {
        instance = [[QLRecordPlayer alloc] init];
    }
    return instance;
}

- (id)init
{
    self = [super init];
    if (self) {

    }
    return self;
}

- (void)play:(NSURL *)url
{
//    url = [NSURL URLWithString: @"http://pic.vsmu.cn/upload/20150403/201504030047280583.spx?tLong%5Cu003d10%5Cu0026random%5Cu003d0.9751111201370921"];
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //类别要AVAudioSessionCategoryPlayAndRecord，才有效
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url.absoluteString]];
    AFURLConnectionOperation *operation =   [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:[self getFilePath] append:NO];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        
    }];
    [SVProgressHUD show];
    [operation setCompletionBlock:^{
        [SVProgressHUD dismiss];
        NSString *path = [self getFilePath];
        [[OggPlayerManager sharedManager] playAudioWithFileName:path delegate:self];
    }];
    [operation start];
}

- (NSString*)getFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"tmp.spx"];
    return filePath;
}

- (void)stop
{
    [[OggPlayerManager sharedManager] stopPlaying];
}

- (void)playingStoped {
    [SVProgressHUD showSuccessWithStatus:@"播放完成"];
}

@end
